package com.yoyo.lib.net;

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

import com.yoyo.lib.AppException;
import com.yoyo.lib.AppException.ErrorType;

public class HttpUtil {

    public static HttpResponse execute(RequestInformation request) throws AppException {
        if (request.mRequestMethod.equals(RequestInformation.REQUEST_METHOD_GET)) {
            return get(request);
        } else if (request.mRequestMethod.equals(RequestInformation.REQUEST_METHOD_POST)) {
            return post(request);
        } else {
            throw new RuntimeException("request method:" + request.mRequestMethod + "is not supported");
        }
    }

    private static HttpResponse get(RequestInformation request) throws AppException {

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(request.url);
        if (request.headers != null && request.headers.size() > 0) {
            for (Map.Entry<String, String> header : request.headers.entrySet()) {
                httpGet.addHeader(header.getKey(), header.getValue());
            }
        }

        request.requestCallback.checkIsCancelled();
        HttpResponse httpResponse = null;

        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (ClientProtocolException e) {
            throw new AppException(ErrorType.ConnectionException, "ClientProtocolException", e.getMessage(),
                    null);
        } catch (IOException e) {
            throw new AppException(ErrorType.ConnectionException, "IOException", e.getMessage(), null);
        }

        return httpResponse;
    }
    
    
    private static HttpResponse post(RequestInformation request) throws AppException {
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            if (request.urlParameters != null && request.urlParameters.size() > 0) {
                Object object = new UrlEncodedFormEntity(request.urlParameters, request.encoding);
            }
            
            HttpPost httpPost = new HttpPost(request.url);
            
            request.requestCallback.checkIsCancelled();
            
            httpResponse = httpClient.execute(httpPost);
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        
        return httpResponse;
    }

}